package com.xiezc.data.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiezc.common.entity.Chapter;
import com.xiezc.common.result.ListResult;
import com.xiezc.common.result.PojoResult;
import com.xiezc.data.service.ChapterService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 章节表 前端控制器
 * </p>
 *
 * @author xiezc
 * @since 2018-10-06
 */
@RestController
@RequestMapping("/chapter")
public class ChapterController {

    @Resource
    ChapterService chapterService;

    @PostMapping("add")
    public PojoResult<Integer> addChapter(@RequestBody Chapter chapter) {

        boolean save = chapterService.save(chapter);
        if (save) {
            return PojoResult.success(chapter.getId());
        } else {
            PojoResult p = new PojoResult<>();
            p.setCode("500");
            p.setErrorMsg("save error");
            return p;
        }
    }

    @GetMapping("getAllByBookId")
    public ListResult<String> getAllByBookId(Integer bookId) {

        LambdaQueryWrapper<Chapter> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Chapter::getFetchUrl).eq(Chapter::getBookId, bookId);
        List<Chapter> list = chapterService.list(queryWrapper);
        Set<String> collect = list
            .parallelStream()
            .map(chapter -> chapter.getFetchUrl())
            .collect(Collectors.toSet());
        return ListResult.success(collect);

    }

    @GetMapping("getByUrl")
    public PojoResult<Chapter> getByUrl(String url) {
        LambdaQueryWrapper<Chapter> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Chapter::getFetchUrl, url);
        Chapter one = chapterService.getOne(wrapper);
        return PojoResult.success(one);
    }
}

